import http from '@/utils/http'
import { getToken, removeToken, setToken } from '@/utils/cookies'
import { TokenKey, SomTokenKey } from '@/const/keys'
import router, { resetRouter } from '@/router'
import { mts } from '../types'
// const inLogin = () => {
// 	const currentHash = decodeURIComponent(location.hash).split('#')[1]

// 	const aUrl = currentHash ? currentHash.split('?') : []

// 	return aUrl.includes('/login')
// }

const state = () => ({
  token: getToken(),
  tokenHead: '',
  avatar: '',
  name: 'Super Admin',
  // introduction: '',
  roles: [],
  // 存储用户菜单权限
  permissions: [],
  sysUser: {},

  // self service
  userInfo: null
})

const mutations = {
  [mts.setPermissions]: (state, permissions = []) => {
    state.permissions = []

    permissions.forEach((element) => {
      state.permissions.push(element)
    })
  },
  [mts.setSysUser]: (state, user) => {
    state.sysUser = user
  },

  [mts.setToken]: (state, token) => {
    state.token = token
  },
  [mts.setTokenHead]: (state, token) => {
    state.tokenHead = token
  },
  [mts.setName]: (state, name) => {
    state.name = name
  },
  [mts.setAvatar]: (state, avatar) => {
    state.avatar = avatar
  },
  [mts.setRoles]: (state, roles = []) => {
    roles.forEach((element) => {
      state.roles.push(element)
    })
  },
  // self service
  [mts.setUserInfo]: (state, user) => {
    state.userInfo = user
  }
}

const actions = {
  resetUser({ commit, dispatch }) {
    commit('setUserInfo', null)
    sessionStorage.setItem('TableColumn', null)
    dispatch('permission/cleanRemoteRoute', null, { root: true })
    dispatch('permission/resetFetchCount', null, { root: true })
  },

  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      http
        .login(userInfo)
        .then((response) => {
          const { code, data } = response
          if (code === 200) {
            commit(mts.setToken, data?.token)
            commit(mts.setTokenHead, data?.tokenHead)
            setToken(data?.token, data?.tokenHead)
            sessionStorage.setItem('login', 'true')
            resolve(response)
            return
          }
          reject(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // sso统一登录设置token
  loginFromSSO({ commit }, tokenInfo) {
    commit(mts.setToken, tokenInfo?.token)
    commit(mts.setTokenHead, tokenInfo?.tokenHead)
    setToken(tokenInfo?.token, tokenInfo?.tokenHead)
    sessionStorage.setItem('login', 'true')
  },

  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit(mts.setToken, '')
      commit(mts.setRoles, [])
      removeToken(TokenKey)
      resolve()
    })
  },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      http
        .getInfo()
        .then((response) => {
          const { data } = response

          if (!data || data === 'null') {
            // data = { roles: [], permissions: [], sysUser: {} }
            return reject('Verification failed, please Login again.')
          }

          const { roles, permissions, sysUser } = data

          commit(mts.setRoles, roles)
          commit(mts.setPermissions, permissions)
          commit(mts.setSysUser, sysUser)

          const { username, avatar } = sysUser

          commit(mts.setAvatar, avatar)
          commit(mts.setName, username)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  getUserInfo({ state }) {
    return new Promise((resolve, reject) => {
      if (state.userInfo) {
        resolve(state.userInfo)
      } else {
        http.getInfo().then((res) => {
          const { data } = res
          resolve(data)
        })
      }
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      const accessToken = getToken(TokenKey)
      removeToken(SomTokenKey)
      dispatch('resetUser')
      fetch(http.logoutUrl.url + '&logout_token=' + accessToken, {
        method: 'POST'
      })
        .then((body) => {
          removeToken(TokenKey)
          router.push({ path: '/login' })
        })
        .catch(() => {
          removeToken(TokenKey)
          router.push({ path: '/login' })
        })
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, state, dispatch }, type = '') {
    resetRouter()
    const accessRoutes = await dispatch('permission/generateRoutes', type, {
      root: true
    })
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
